package it.niedermann.android.markdown.markwon.span

import android.text.style.URLSpan
import android.view.View
import timber.log.Timber
import java.util.concurrent.Executors
import java.util.function.Function

class InterceptedURLSpan(
    private val onLinkClickCallbacks: Collection<Function<String, Boolean>>,
    url: String?
) : URLSpan(url) {
    private val executor = Executors.newCachedThreadPool()
    override fun onClick(widget: View) {
        if (onLinkClickCallbacks.isNotEmpty()) {
            executor.submit {
                for (callback in onLinkClickCallbacks) {
                    try {
                        if (callback.apply(url)) {
                            return@submit
                        }
                    } catch (t: Throwable) {
                        Timber.tag(TAG).w(t)
                    }
                }
                super.onClick(widget)
            }
        } else {
            super.onClick(widget)
        }
    }

    companion object {
        private val TAG = InterceptedURLSpan::class.java.simpleName
    }
}